public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val){
            this.val = val;
        }
    }
    public TreeNode root;
    public boolean search(int val){
        TreeNode cur = root;
        while (cur!=null) {
            if (val > cur.val) {
                //找右子树
                cur = cur.right;
            } else if (val < cur.val) {
                //找左子树
                cur=cur.left;
            } else {
                return true;
            }
        }

        return false;
    }

    public void insert(int val){
        if(root==null){
            root = new TreeNode(val);
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur!=null){
            if (val > cur.val) {
                parent=cur;
                cur = cur.right;
            } else if (val < cur.val) {
                parent=cur;
                cur = cur.left;
            } else {
                return;
            }
        }

        TreeNode node = new TreeNode(val);
        if (parent.val<val){
            parent.right=node;
        }else{
            parent.left=node;
        }
    }


    public void remode(int val){
        //前提是二叉树是搜索树
        TreeNode cur = root;
        TreeNode parent =null;
        while(cur!=null){
            if(cur.val<val){
                //证明要删除的在cur的右边
                parent = cur;
                cur = cur.right;
            }else if(cur.val>val){
                //证明要删除的在cur的左边
                parent = cur;
                cur = cur.left;
            }else{
                //此时要删除的就是cur
                removeNode(parent,cur);
                return;
            }
        }
    }
    private void removeNode(TreeNode parent,TreeNode cur){
        //分三种
        if(cur.left==null){
            if(cur==root){
                root = cur.right;
            }else if(cur==parent.left){
                parent.left=cur.right;
            }else{
                parent.right = cur.right;
            }
        }else if(cur.right==null){
            if(cur==root){
                root = cur.left;
            }else if(cur ==parent.left){
                parent.left = cur.left;
            }else{
                parent.right = cur.left;
            }
        }else{
            //左右都不为空,直接替换删除
            TreeNode t = cur.right;
            TreeNode tp = cur;
            while(t.left!=null){
                tp = t;
                t = t.left;
            }
            cur.val = t.val;
            if(tp.left ==t){
                tp.left = t.right;
            }else{
                tp.right = t.right;
            }
        }
    }
}
